import * as THREE from "three";

export default class InteractionHandler {
  constructor(scene, camera, renderer, config) {
    this.scene = scene;
    this.camera = camera;
    this.renderer = renderer;
    this.config = config;
    this.raycaster = new THREE.Raycaster();
    this.mouse = new THREE.Vector2();
    this.currentSelection = null;
    this.eventListeners = new Map();
  }

  setupEventListeners() {
    this.addListener(window, 'resize', this.handleResize.bind(this));
    this.addListener(this.renderer.domElement, 'click', this.handleClick.bind(this));
  }

  addListener(target, type, handler) {
    target.addEventListener(type, handler);
    this.eventListeners.set(handler, { target, type });
  }

  handleResize() {
    // 由主组件统一处理
  }

  handleClick(event) {
    this.updateMousePosition(event);
    const intersects = this.getIntersections();
    
    if (intersects.length > 0) {
      const selected = this.findSelectableParent(intersects[0].object);
      if (selected) {
        this.processSelection(selected);
      }
    } else {
      this.clearSelection();
    }
  }

  findSelectableParent(object) {
    while (object) {
      if (object.userData?.selectable) return object;
      object = object.parent;
    }
    return null;
  }

  updateMousePosition(event) {
    const rect = this.renderer.domElement.getBoundingClientRect();
    this.mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
    this.mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
  }

  getIntersections() {
    this.raycaster.setFromCamera(this.mouse, this.camera);
    return this.raycaster.intersectObjects(this.scene.children, true);
  }

  processSelection(object) {
    if (this.currentSelection) {
      this.clearSelection();
    }
    
    // 高亮选中对象
    if (object.material) {
      object.material.color.set(this.config.map.areaColors.highlight);
    }
    this.currentSelection = object;
  }

  clearSelection() {
    if (this.currentSelection?.material) {
      this.currentSelection.material.color.set(this.config.map.areaColors.top);
    }
    this.currentSelection = null;
  }

  dispose() {
    this.eventListeners.forEach(({ target, type }, handler) => {
      target.removeEventListener(type, handler);
    });
    this.eventListeners.clear();
  }
}